package service

import (
	"errors"
	"strconv"
	"time"

	"github.com/golang-jwt/jwt/v4"
	"good.house/internal/dto/request"
	"good.house/internal/model"
	"good.house/internal/repository"
	"good.house/internal/utils"
)

type UserService struct {
	repository repository.IUserRepository
}

func NewUserService(r repository.IUserRepository) *UserService {
	return &UserService{
		repository: r,
	}
}

func (s *UserService) Register(data *request.RegisterRequest) error {
	count := s.repository.GetCountByUsername(data.Username)

	if count > 0 {
		return errors.New("用户名已存在")
	}

	count = s.repository.GetCountByMobile(data.Mobile)

	if count > 0 {
		return errors.New("手机号已存在")
	}
	return s.repository.Create(&model.User{
		Username: data.Username,
		Password: data.Password,
		Mobile:   data.Mobile,
		UserType: data.UserType,
	})
}

func (s *UserService) Login(data *request.LoginRequest, secretKey string) (user *model.User, token string, err error) {
	user, err = s.repository.FindUserByUsername(data.Username)

	if err != nil {
		return user, "", err
	}

	if user.Username == "" {
		return user, "", errors.New("用户不存在")
	}

	passwrod := utils.HashPassowrd(data.Password, user.Salt)

	if passwrod != user.Password {
		return user, "", errors.New("密码错误")
	}

	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": user.Username,
		"id":       user.ID,
		// "exp":      time.Now().Add(1 * time.Hour).Unix(),
		"iat": time.Now().Unix(),
	})

	tokenString, err := jwtToken.SignedString([]byte(secretKey))

	if err != nil {
		return user, "", err
	}

	setTokenErr := s.repository.SetTokenId(strconv.FormatInt(user.ID, 10))

	if setTokenErr != nil {
		return user, "", setTokenErr
	}

	return user, tokenString, err
}
